package org.deng.vertx.springboot.verticle;

import io.vertx.core.DeploymentOptions;
import lombok.extern.slf4j.Slf4j;
import org.deng.vertx.springboot.verticle.service.BaseServiceVerticle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 邓力宾
 * @date 2022/12/28 16:35
 * @desc
 */
@Component
@Slf4j
public class MainVerticle extends BaseVerticle implements ApplicationContextAware {

    private WebVerticle webVerticle;

    private ApplicationContext applicationContext;

    @Autowired
    public void setWebVerticle(WebVerticle webVerticle) {
        this.webVerticle = webVerticle;
    }

    @Override
    public void start() throws Exception {
        log.info("MainVerticle start方法");

        //部署service Verticle
        deployServiceVerticle();

        //部署webVerticle
        deployWebVerticle();


    }

    /**
     * 部署webVerticle
     */
    private void deployWebVerticle(){
        //web verticle
        vertx.deployVerticle(webVerticle, result->{
            if(result.succeeded()){
                log.info("部署webVerticle成功");
            }
        });


    }

    /**
     * 部署service verticle
     */
    private void deployServiceVerticle(){
        DeploymentOptions deploymentOptions = new DeploymentOptions();
        deploymentOptions.setWorker(true);
        Map<String, BaseServiceVerticle> serviceVerticleMap = applicationContext.getBeansOfType(BaseServiceVerticle.class);
        for (Map.Entry<String, BaseServiceVerticle> entry : serviceVerticleMap.entrySet()) {
            BaseServiceVerticle baseServiceVerticle = entry.getValue();
            vertx.deployVerticle(baseServiceVerticle, deploymentOptions, res->{
                log.info("部署serviceVerticle::{}成功", baseServiceVerticle.getClass().getName());
            });
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
